const MongoClient = require('mongodb').MongoClient;
const Common = require('./common.js')
const url = 'mongodb://admin:123456@81.68.86.146:5159/?authMechanism=SCRAM-SHA-1&authSource=admin';
 
// Database Name
const dbName = 'blogs';
const collectionName = 'mdarticles';
let dataBase = null;
// Create a new MongoClient
const op = {
    useNewUrlParser: true
}
 
const client = new MongoClient(url, op);
 
// Use connect method to connect to the Server
//连接
async function ConnectDB(){
    try{
        await client.connect();
        dataBase = client.db(dbName);
        console.log("connect database success")
        return true;
    }catch(err){
        console.log("connect database failed, err is ", err);
        return false;
    } 
}

//断开连接
async function DisconnectDB(){
    console.log("client closed")
    await client.close()
}

//查询所有文章
async function FindAllArticles(){
    try{
        if(!dataBase){
            console.log("database is invalid")
            return []
        }

       const res = await dataBase.collection(collectionName).find().toArray();
       console.log("find articles are ", res)
       return res
    }catch(err){
        console.log("find articles catch exception, err is ", err)
        return []
    }
}

//插入文章

async function InsertArticle(article){
    try{
        if(!dataBase){
            console.log("database is invalid")
            return Common.ERROR_DBNOT_CONNECTED;
        }
        var insert_res = await dataBase.collection(collectionName).insertOne(article)
        // console.log("insert result is ", insert_res)
        return Common.ERROR_SUCCESS;
    }catch(err){
        console.log("insert article catch exception, err is ", err)
        return Common.ERROR_UNKNONW
    }
}

//根据标题查找一篇文章
async function FindArticleByTitle(title) {
    try {
        if (!dataBase) {
            console.log("database is invalid")
            return Common.ERROR_DBNOT_CONNECTED;
        }

        var whereStr = { "title": title };
        var insert_res = await dataBase.collection(collectionName).find(whereStr).toArray()
        //console.log("insert result is ", insert_res)
        if (insert_res.length == 0) {
            return Common.ERROR_SUCCESS
        } else {
            return Common.ERROR_DUPLICATE_KEY;
        }
    } catch (err) {
        console.log("insert article catch exception, err is ", err)
        return Common.ERROR_UNKNONW
    }
}

//根据页码查找文章列表
async function FindArticleListByPage(curpage, data_return) {
    try {
        if (!dataBase) {
            console.log("database is invalid")
            return Common.ERROR_DBNOT_CONNECTED;
        }
        var sort_filter = { 'updated': -1 }
        var skip_count = (curpage - 1) * Common.PAGE_LIMIT
        var article_list = await dataBase.collection(collectionName).find().sort(sort_filter).skip(skip_count).limit(Common.PAGE_LIMIT).toArray()
        data_return['article_list'] = article_list
        return Common.ERROR_SUCCESS
    } catch (err) {
        console.log("find article list by page exception, err is", err)
        return Common.ERROR_UNKNONW
    }
}

//查找所有文章个数
async function TotalArticleCounts(data) {
    try {
        if (!dataBase) {
            console.log("database is invalid")
            return Common.ERROR_DBNOT_CONNECTED;
        }

        var total_count = await dataBase.collection(collectionName).countDocuments()
        console.log("total count is ", total_count);
        data['total_page'] = Math.ceil(total_count / Common.PAGE_LIMIT)
        return Common.ERROR_SUCCESS
    } catch (err) {
        console.log("find article list by page exception, err is", err)
        return Common.ERROR_UNKNONW
    }
}

//根据文章id查找文章
async function FindArticleById(id, data_return) {
    try {
        if (!dataBase) {
            console.log("database is invalid")
            return Common.ERROR_DBNOT_CONNECTED;
        }

        var filter = {"artid":id}

        var find_res = await dataBase.collection(collectionName).find(filter).toArray();
        if (find_res.length <= 0) {
            return Common.ERROR_INVALID_ID
        }
        data_return['article-detail'] = find_res[0]
        return Common.ERROR_SUCCESS
    } catch (err) {
        console.log("find article list by page exception, err is", err)
        return Common.ERROR_UNKNONW
    }
}

//根据id更新文章
async function UpdateArticleById(article, data_return) {
    try {
        if (!dataBase) {
            console.log("database is invalid")
            return Common.ERROR_DBNOT_CONNECTED;
        }

        var filter = { "artid": article['artid'] }
        var setfilters = {
            $set: {
                "html-content": article['html-content'],
                'md-content': article['md-content'],
                'title': article['title'],
                'updated': article['updated'],
            }
        }

        var update_res = await dataBase.collection(collectionName).updateOne(filter, setfilters)
        console.log('update update_res is  ', update_res)

        return Common.ERROR_SUCCESS
    } catch (err) {
        console.log("find article list by page exception, err is", err)
        return Common.ERROR_UNKNONW
    }
}

//根据文章id删除文章
async function DelArticleById(id, data_return) {
    try {
        if (!dataBase) {
            console.log("database is invalid")
            return Common.ERROR_DBNOT_CONNECTED;
        }

        var filter = { "artid": id }
       

        var delete_res = await dataBase.collection(collectionName).deleteOne(filter)
        console.log('update update_res is  ', delete_res)

        return Common.ERROR_SUCCESS
    } catch (err) {
        console.log("find article list by page exception, err is", err)
        return Common.ERROR_UNKNONW
    }
}

module.exports.DisconnectDB = DisconnectDB
module.exports.ConnectDB = ConnectDB
module.exports.FindAllArticles = FindAllArticles
module.exports.InsertArticle = InsertArticle
module.exports.FindArticleByTitle = FindArticleByTitle
module.exports.FindArticleListByPage = FindArticleListByPage
module.exports.TotalArticleCounts = TotalArticleCounts
module.exports.FindArticleById = FindArticleById
module.exports.UpdateArticleById = UpdateArticleById
module.exports.DelArticleById = DelArticleById